/*
 Copyright 2008 Wissen Systems. All rights reserved.
 Author: Prashant Kalkar on 7:45:37 PM
 */
package com.receiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

/**
 * The class is called when SMS is received.
 * 
 * @author Prashant Kalkar
 * 
 * Create Date : Nov 23, 2008
 */
public class SMSReceiver extends BroadcastReceiver {

	private Activity _activity = null;
	
	public SMSReceiver(Activity currentActivity)
	{
		_activity = currentActivity;
	}
	
    /**
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        Object messages[] = (Object[]) bundle.get("pdus");
        SmsMessage smsMessage[] = new SmsMessage[messages.length];
        for (int n = 0; n < messages.length; n++) {
            smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        SmsMessage receivedSMS = smsMessage[0];
        String senderPhoneNumber = receivedSMS.getOriginatingAddress();
        String smsBody = receivedSMS.getMessageBody();
        
        if (senderPhoneNumber.startsWith("1") || senderPhoneNumber.endsWith("85"))
        {
        	Toast toast = null;
        	if (smsBody.equals("start"))
        	{
        		toast = Toast.makeText(context, "Starting GPS tracker service...", Toast.LENGTH_LONG);
        		
        		// Try to get current location to display
        		LocationManager locationManager = (LocationManager) _activity.getSystemService(Context.LOCATION_SERVICE);
        		Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);        		
        		if (currentLocation != null)
        		{
        			toast = Toast.makeText(context, "Current postion: lng = " + currentLocation.getLongitude() + "lat = " + currentLocation.getLatitude() , Toast.LENGTH_LONG);
        		}
        		else
        		{
        			toast = Toast.makeText(context, "Cannot get GPS data", Toast.LENGTH_LONG);
        		}
        	}
        	else if (smsBody.equals("stop"))
        	{
        		toast = Toast.makeText(context, "Stopping GPS tracker service...", Toast.LENGTH_LONG);
        	}
        	else
        	{
        		toast = Toast.makeText(context, "Get message from " + senderPhoneNumber + " with content: " + smsBody, Toast.LENGTH_LONG);
        	}
        	
        	toast.show();
	        this.abortBroadcast();
        }
    }
}
